package com.cloudkinto.service.platform.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.RabbitQueueConstant;
import com.cloudkinto.common.RedisKeyConstants;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.HmacUtil;
import com.cloudkinto.common.utils.OkHttpUtils;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.dao.*;
import com.cloudkinto.dto.platform.PlatOrderUpdateTimeDto;
import com.cloudkinto.dto.platform.order.PlatOrderPageRes;
import com.cloudkinto.entity.*;
import com.cloudkinto.enumType.common.CountryEnum;
import com.cloudkinto.enumType.operate.OperateTypeEnum;
import com.cloudkinto.service.consumer.vo.orderSyncRecord.PlatformOrderSyncRecordReq;
import com.cloudkinto.service.consumer.vo.rakuten.RakutenOrderUpdateConReq;
import com.cloudkinto.service.consumer.vo.shopify.ShopifyConsumerReq;
import com.cloudkinto.service.platform.PlatformOrderService;
import com.cloudkinto.service.platform.PlatformOrderShopifySyncService;
import com.cloudkinto.service.platform.PlatformStoreService;
import com.cloudkinto.service.platform.sync.vo.SyncRecordItemReq;
import com.cloudkinto.service.platform.vo.shopify.OrderShopifyEntity;
import com.cloudkinto.service.platform.vo.shopify.ShippingAddressEntity;
import com.cloudkinto.service.platform.vo.shopify.fulfillment.FulfillmentOrderLineItems;
import com.cloudkinto.service.platform.vo.shopify.fulfillment.LineItemsByFulfillmentOrder;
import com.cloudkinto.service.platform.vo.shopify.fulfillment.ShopifyAddFulfillment;
import com.cloudkinto.service.platform.vo.shopify.fulfillment.TrackingInfo;
import com.cloudkinto.service.platform.vo.shopify.fulfillment.reponse.OrderFulfillmentOrderEntity;
import com.cloudkinto.service.platform.vo.store.StoreShopifyAddReq;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author ding
 * @since 2021-09-23
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
@RequiredArgsConstructor
public class PlatformOrderShopifySyncServiceImpl extends ServiceImpl<PlatformOrderDao, PlatformOrderDo> implements PlatformOrderShopifySyncService {
    private final PlatformStoreDao platformStoreDao;
    private final PlatformOrderDao platformOrderDao;
    private final RabbitTemplate rabbitTemplate;
    private final PlatformOrderProductDao platformOrderProductDao;
    private final PlatformOrderService platformOrderService;
    private final PlatformStoreService platformStoreService;
    protected final RedisTemplate redisTemplate;
    private final PlatformOrderTrackDao platformOrderTrackDao;
    @Value("${gbc.customer}")
    private String customer;
    private final PlatformOrderSyncRecordDao platformOrderSyncRecordDao;


    protected String AUTHORIZESTATEKEY = "yahoo_authorize_state_";
    /**
     * ===========================Shopify参数================================
     */
    protected  String ShopifySecret = "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";
    protected  String ShopifyKey = "fd5b9cb19a9ab8d8223bf2f5283d3740";

    /**
     * shopify授权第一步 返回给前端跳转的url
     */
    @Override
    public String authorizeNow(StoreShopifyAddReq req, Long userId, Long companyId) {
        boolean check = platformStoreService.check(req.getId(), req.getStoreCode(), companyId);
        if (!check) {
            throw new BizException("店铺代码已存在");
        }
        if (req.getId() != null) {
            PlatformStoreDo storeDo = platformStoreService.getById(req.getId());
            if (storeDo == null || !Objects.equals(storeDo.getCompanyId(), companyId)) {
                throw new BizException("店铺不存在");
            }
        }
        String state = UUID.randomUUID().toString();
        //放入缓存
        redisTemplate.opsForValue().set(AUTHORIZESTATEKEY + userId, state, 3000, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(state, JSON.toJSONString(req), 3000, TimeUnit.SECONDS);
        StringBuilder builderUrl = new StringBuilder();
        builderUrl.append("https://").append(req.getAppKey()).append(".myshopify.com/admin/oauth/authorize")
                .append("?clientId=").append(ShopifyKey)
                .append("&grant_options[]=null")
                .append("&redirect_uri=https://www.cloudkinto.com/kinto/KeyBinding")
                .append("&scope=read_orders,read_all_orders,read_merchant_managed_fulfillment_orders,write_merchant_managed_fulfillment_orders,read_assigned_fulfillment_orders,write_assigned_fulfillment_orders,read_third_party_fulfillment_orders,write_third_party_fulfillment_orders,read_products,read_locations,read_inventory,write_inventory")
                .append("&state=").append(state);
        //todo redirect_uri 值不知道是什么
        return builderUrl.toString();
    }



    @Override
    public void getShopifyAuthorizeMsg(Long companyId, String code, String
            session, String state, String host, String hmac, String shop, String timestamp, Long userId) {
        Object value = redisTemplate.opsForValue().get(state);
        if (value == null) {
            throw new BizException("未找到店铺,授权失败");
        }
        StoreShopifyAddReq storeShopifyAddReq = JSON.parseObject(value.toString(), StoreShopifyAddReq.class);

        StringBuilder data = new StringBuilder();
        if (StringUtils.isNotBlank(code)) {
            data.append("code=").append(code);
        }
        if (StringUtils.isNotBlank(host)) {
            data.append("&");
            data.append("host=").append(host);
        }
        if (StringUtils.isNotBlank(session)) {
            data.append("&");
            data.append("session=").append(session);
        }
        if (StringUtils.isNotBlank(shop)) {
            data.append("&");
            data.append("shop=").append(shop);
        }
        if (StringUtils.isNotBlank(state)) {
            data.append("&");
            data.append("state=").append(state);
        }
        if (StringUtils.isNotBlank(timestamp)) {
            data.append("&");
            data.append("timestamp=").append(timestamp);
        }
        if (data.toString().startsWith("&")) {
            data.replace(0, 1, "");
        }
//        if (true) return SingleResult.failure("504", "授权失败,请重试");
        try {
            if (!HmacUtil.HMACSHA256(data.toString(), ShopifySecret).equals(hmac)) {
                throw new BizException("auth.error");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String body = "";


        String url = "https://" + shop + "/admin/oauth/access_token";
        OkHttpClient.Builder client = this.getHttpClient();
        System.out.println(url);
        Map<String, String> params = new HashMap<>();
        params.put("client_id", ShopifyKey);
        params.put("client_secret", ShopifySecret);
        params.put("code", code);
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .post(RequestBody.create(MediaType.get("application/json"), JSON.toJSONString(params)))
                .url(url)
                .build();
        Response response = null;

        try {
            response = client.build().newCall(request).execute();
            if (response.body() != null) {
                body = response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(body)) {
            throw new BizException("连接超时,shopify授权失败");
        }
        //{
        //    "access_token": "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",
        //    "scope": "write_orders,read_customers"
        //}
        JSONObject jsonObject = JSON.parseObject(body);
        String accessToken = jsonObject.getString("access_token");
        if (StringUtils.isNotBlank(accessToken)) {
            throw new BizException("无accessToken,shopify授权失败");
        }
        PlatformStoreDo storeDo;
        if (storeShopifyAddReq.getId() == null) {
            storeDo = platformStoreService.shopifyStoreAdd(storeShopifyAddReq, userId);
        } else {
            storeDo = platformStoreService.getById(storeShopifyAddReq.getId());
            if (!Objects.equals(storeDo.getCompanyId(), companyId)) {
                throw new BizException("店铺不存在,shopify授权失败");
            }
        }
        storeDo.setAppSecret(accessToken);
        storeDo.setAuthSyncStatus(1);
        storeDo.setAuthSyncTime(new Date());
        platformStoreDao.updateById(storeDo);
    }



    @Override
    public void platOrderShopifySync() {
        List<PlatformStoreDo> storeDoList = platformStoreDao.selectList(new LambdaQueryWrapper<PlatformStoreDo>().eq(PlatformStoreDo::getPlatformCode, "shopify")
                .eq(PlatformStoreDo::getAuthSyncStatus, 1).isNotNull(PlatformStoreDo::getAppSecret));
        Map<Long, Long> storeRecordIdMap = new HashMap<>();
        for (PlatformStoreDo storeDo : storeDoList) {
            PlatformOrderSyncRecordDo recordDo = new PlatformOrderSyncRecordDo(storeDo.getPlatformCode(), storeDo.getId(), 1, 0, 0, new Date(), null, storeDo.getCompanyId());
            platformOrderSyncRecordDao.insert(recordDo);
            storeRecordIdMap.put(storeDo.getId(), recordDo.getId());
        }
        for (PlatformStoreDo platformStoreDo : storeDoList) {
            Long syncRecordId = storeRecordIdMap.get(platformStoreDo.getId());
            if (syncRecordId == null) {
                continue;
            }
            ShopifyConsumerReq consumerReq = new ShopifyConsumerReq(platformStoreDo.getId(), null, null, syncRecordId);
            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformStore_Shopify_Sync, JSON.toJSONString(consumerReq));
        }
    }


    @Override
    public String updateShopifyOrders(ShopifyConsumerReq req) {
        PlatformStoreDo storeDo = platformStoreDao.selectById(req.getStoreId());
        if (storeDo == null) {
            return SysConstant.Shop_NotExist;
        }
        boolean flag = req.getStartDate() == null;
        //自动
        if (!flag) {
            long l = DateUtil.betweenDay(req.getStartDate(), req.getEndDate(), true);
            if (l > 7) {
                return "店铺:"+storeDo.getStoreName() +"每次最多同步7天数据";
            }
        }
        if (flag) { //自动
            Double time = redisTemplate.opsForZSet().score(RedisKeyConstants.orderSyncTimeSet_Shopify + customer, storeDo.getId());
            long currency = System.currentTimeMillis();
            if (!(time == null || (currency - time) >= 60 * 10 * 1000)) {
//                return "shopify 同步频率过快(10分钟同步一次)";
            }
            //无上次同步时间 或者 上次同步时间在10分钟之前
            redisTemplate.opsForZSet().add(RedisKeyConstants.orderSyncTimeSet_Shopify + customer, storeDo.getId(), currency - 10 * 1000);
            if (time == null) {
                req.setStartDate(DateUtils.passingDateHour(new Date(), -16));
            } else {
                req.setStartDate(new Date(time.longValue() - 60 * 1000 * 21));
            }
            long l = DateUtil.betweenDay(req.getStartDate(), new Date(), true);
            if (l > 2) {
                req.setStartDate(DateUtils.passingDate(new Date(), -2));
            }
        }
        String url = "https://" + storeDo.getAppKey() + ".myshopify.com/admin/api/2023-07/orders.json?status=any";
        Map<String, String> bodyMap = null;
        //告诉他正在处理
        rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformOrder_SyncRecord_Update, JSON.toJSONString(new PlatformOrderSyncRecordReq(req.getSyncId(), 1, new Date(), req.getStartDate(), req.getEndDate())));
        List<OrderShopifyEntity> entities = new ArrayList<>();
        do {
            if (bodyMap != null) {
                url = bodyMap.get("page");
            }
            bodyMap = this.httpGet(url, storeDo, req.getStartDate(), req.getEndDate());
            if (bodyMap == null) {
                if (flag) {
                    redisTemplate.opsForZSet().add(RedisKeyConstants.orderSyncTimeSet_Shopify+ customer, storeDo.getId(), req.getStartDate().getTime());
                }
                break;
            }
            String body = bodyMap.get("body");
            if (StringUtils.isBlank(body)) {
                if (flag) {
                    redisTemplate.opsForZSet().add(RedisKeyConstants.orderSyncTimeSet_Shopify+ customer, storeDo.getId(), req.getStartDate().getTime());
                }
                break;
            }
            JSONObject error = null;
            try {
                 error = JSONObject.parseObject(body);
            } catch (Exception e) {
                e.printStackTrace();
                if (flag) {
                    redisTemplate.opsForZSet().add(RedisKeyConstants.orderSyncTimeSet_Shopify+ customer, storeDo.getId(), req.getStartDate().getTime());
                }
                return "JSONObject Body 错误";
            }
            if (error != null && error.get("errors") != null) {
                log.error(error.getString("errors"));
                if ("[API] Invalid API key or access token (unrecognized login or wrong password)".equals(error.getString("errors"))) {
                    //todo 授权失效
                }
                if (flag) {
                    redisTemplate.opsForZSet().add(RedisKeyConstants.orderSyncTimeSet_Shopify+ customer, storeDo.getId(), req.getStartDate().getTime());
                }
                return error.getString("errors");
            }
            JSONArray jsonArray = JSONObject.parseObject(bodyMap.get("body")).getJSONArray("orders");
            if (jsonArray == null) {
                if (flag) {
                    redisTemplate.opsForZSet().add(RedisKeyConstants.orderSyncTimeSet_Shopify+ customer, storeDo.getId(), req.getStartDate().getTime());
                }
                return "jsonArray 解析返回空";
            }
            List<OrderShopifyEntity> orderShopifyEntities = JSON.parseArray(jsonArray.toJSONString(), OrderShopifyEntity.class);
//            orderFiledIds.addAll(handlerSyncAfter(orderShopifyEntities, shopDo));
            entities.addAll(orderShopifyEntities);
        } while (StringUtils.isNotBlank(bodyMap.get("page")));

        //获取这些订单的 最近更新时间
        List<String> platformOrders = entities.stream().map(i -> String.valueOf(i.getOrder_number())).collect(Collectors.toList());
        Map<String, PlatOrderUpdateTimeDto> orderMap = new HashMap<>();
        if (!platformOrders.isEmpty()) {
            List<List<String>> partition = ListUtil.partition(platformOrders, 5000);
            for (List<String> list : partition) {
                List<PlatOrderUpdateTimeDto> platOrder = platformOrderDao.getPlatOrder(list, storeDo.getId(), "shopify");
                orderMap.putAll(platOrder.stream().collect(Collectors.toMap(PlatOrderUpdateTimeDto::getPlatformOrderNo, i -> i)));
            }
        }

        //组装
        //要插入的
        List<PlatformOrderDo> platInertList = new ArrayList<>();
        //要更新 子表的的
        List<PlatformOrderDo> platUpdateList = new ArrayList<>();

        //子表插入的
        List<PlatformOrderProductDo> platInsertItems = new ArrayList<>();
        List<PlatformOrderProductDo> platUpdateItems = new ArrayList<>();

//        List<OrderIdEntity> toUpdateItemOrderIds = new ArrayList<>();
        for (OrderShopifyEntity amzOrder : entities) {
            Date platUpdateTIme = amzOrder.getUpdated_at();

            PlatOrderUpdateTimeDto oldUpdateTime = orderMap.get(String.valueOf(amzOrder.getOrder_number()));
            //如果最近更新时间 和子表都同步下来了 就不需要在操作了
            if (oldUpdateTime != null && Objects.equals(oldUpdateTime.getLastUpdateDate().getTime(), platUpdateTIme.getTime())) {
                //更新日期相等
                continue;
            }

            PlatformOrderDo orderDo = new PlatformOrderDo();
            orderDo.setReserveFlag(0);
            orderDo.setCompanyId(storeDo.getCompanyId());
            orderDo.setTenantId(storeDo.getTenantId());
            orderDo.setPlatformCode(storeDo.getPlatformCode());
            orderDo.setStoreId(storeDo.getId());
            orderDo.setSite(storeDo.getSite());
            orderDo.setOrderTime(amzOrder.getCreated_at());
            orderDo.setPayTime(amzOrder.getProcessed_at());
            orderDo.setLastUpdateDate(platUpdateTIme);
            orderDo.setPlatformOrderNo(String.valueOf(amzOrder.getId()));
            orderDo.setBasketId(String.valueOf(amzOrder.getId()));

            if ("voided".equals(amzOrder.getFinancial_status())) {
                //取消
                orderDo.setStatus(StaticDict.Platform_Order_Status.Four.getValue());
                orderDo.setCancelWay(0);
            } else if ("fulfilled".equals(amzOrder.getFulfillment_status())) {
                orderDo.setStatus(StaticDict.Platform_Order_Status.Three.getValue());
//                orderDo.setMarkShipmentStatus(4);
                //发货时间
            } else {
                if (oldUpdateTime == null) {
                    orderDo.setStatus(StaticDict.Platform_Order_Status.Zero.getValue());
                }
            }

            ShippingAddressEntity shippingAddress = amzOrder.getShipping_address();
            //收货人信息
            if (shippingAddress != null) {
                orderDo.setReceiver(shippingAddress.getName());
                orderDo.setTelephone(shippingAddress.getPhone());
                //todo 转换国家
                if ("Japan".equals(shippingAddress.getCountry())) {
                    orderDo.setCountryRegionCode(CountryEnum.JP.toString());
                }
                else {
                    orderDo.setCountryRegionCode(shippingAddress.getCountry());
                }
                orderDo.setProvinceCode(shippingAddress.getProvince_code());
                orderDo.setProvinceName(shippingAddress.getProvince());
                orderDo.setCityCode(shippingAddress.getCity());
//                orderDo.setDistrict(shippingAddress.getZip());
                orderDo.setPostcode(shippingAddress.getZip());
                orderDo.setHouseNum("");
                orderDo.setAddressOne(shippingAddress.getAddress1());
                orderDo.setAddressTwo(shippingAddress.getAddress2());
            }
            //买家信息
            if (amzOrder.getCustomer() != null) {
                orderDo.setBuyerName(amzOrder.getCustomer().getLastName() + " " + amzOrder.getCustomer().getFirstName());
                orderDo.setBuyerEmail(amzOrder.getCustomer().getEmail());
            }
//            //总金额
            orderDo.setTotalAmount(BigDecimal.valueOf(amzOrder.getSubtotal_price()));
            orderDo.setCurrencyCode(amzOrder.getCurrency());
            orderDo.setRemark(amzOrder.getTags());

            StringBuilder builder = new StringBuilder();
            for (OrderShopifyEntity.Line_itemsEntity line_item : amzOrder.getLine_items()) {
                PlatformOrderProductDo platItem = new PlatformOrderProductDo();
//                platItem.setOrderId(toUpdateItem.getId());
                platItem.setPlatformOrderNo(String.valueOf(amzOrder.getId()));
                platItem.setPlatformSku(line_item.getSku());
                platItem.setPlatformProductName(line_item.getTitle());
                platItem.setPlatformQty(line_item.getQuantity());
                platItem.setSkuType(1);
                platItem.setItemAmount(BigDecimal.valueOf(line_item.getPrice()));
                platItem.setCurrencyCode(amzOrder.getCurrency());
                if (org.apache.commons.lang3.StringUtils.isNotBlank(builder)) {
                    builder.append(";");
                }
                builder.append(platItem.getPlatformSku()).append("*").append(platItem.getPlatformQty());
                if (oldUpdateTime != null) {
                    platItem.setOrderId(oldUpdateTime.getId());
                    platUpdateItems.add(platItem);
                }
                else {
                    platInsertItems.add(platItem);
                }
            }
            if (builder.length() > 100) {
                builder.delete(100, builder.length());
            }
            orderDo.setPlatformSku(builder.toString());
            if (oldUpdateTime != null) {
                orderDo.setId(oldUpdateTime.getId());
                platUpdateList.add(orderDo);
            } else {
                platInertList.add(orderDo);
            }

        }

        if (!platInertList.isEmpty()) {
            platformOrderService.matchSystemSku(platInsertItems, storeDo.getId(), storeDo.getCompanyId(), storeDo.getTenantId());
            Map<String, List<PlatformOrderProductDo>> skuMap = platInsertItems.stream().filter(i -> org.apache.commons.lang3.StringUtils.isNotBlank(i.getSku())).collect(Collectors.groupingBy(PlatformOrderProductDo::getPlatformOrderNo));
            List<PlatformOrderDo> insertList = platInertList.stream().filter(i -> skuMap.containsKey(i.getPlatformOrderNo())).collect(Collectors.toList());
            for (PlatformOrderDo orderDo : insertList) {
                if (skuMap.get(orderDo.getPlatformOrderNo()) == null) {
                    continue;
                }
                StringBuilder builder = new StringBuilder();
                for (PlatformOrderProductDo productDo : skuMap.get(orderDo.getPlatformOrderNo())) {
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(builder.toString())) {
                        builder.append(";");
                    }
                    builder.append(productDo.getSku()).append("*").append(productDo.getQty());
                }
                if (builder.length() > 100) {
                    builder = new StringBuilder(builder.substring(0, 100));
                }
                orderDo.setSku(builder.toString());
            }
            platformOrderDao.insertPlatformOrder(platInertList);
            for (PlatformOrderDo orderDo : platInertList) {
                //去赋值 orderId
                platInsertItems.stream().filter(i -> i.getPlatformOrderNo().equals(orderDo.getPlatformOrderNo())).forEach(item -> item.setOrderId(orderDo.getId()));
            }
        }
        //插入子表
        if (!platInsertItems.isEmpty()) {
//            List<PlatformOrderProductDo> tempPackageList = platInsertItems.stream()
//                    .filter(item -> ObjectUtil.isNotNull(item.getOrderId()))
//                    .collect(Collectors.toList());
//            platformOrderService.matchSystemSku(tempPackageList, req.getStoreId(), storeDo.getCompanyId(), storeDo.getTenantId());
//            if (!tempPackageList.isEmpty()) {
//                platformOrderProductDao.insertPlatformOrderItems(tempPackageList);
//            }
            platformOrderProductDao.insertPlatformOrderItems(platInsertItems);
        }
        //分别去插入更新
        if (!platUpdateList.isEmpty()) {
            //再交给rabbitMq 去更新子表
            for (PlatformOrderDo orderDo : platUpdateList) {
                List<PlatformOrderDo> array = new ArrayList<>(Collections.singletonList(orderDo));
                List<PlatformOrderProductDo> collect = platUpdateItems.stream().filter(i -> Objects.equals(orderDo.getId(), i.getOrderId())).collect(Collectors.toList());
                rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformStore_Shopify_Update, JSON.toJSONString(new RakutenOrderUpdateConReq(array, collect, storeDo.getId(), storeDo.getCompanyId(), storeDo.getTenantId())));
            }
        }
        //完成
        List<SyncRecordItemReq> items = platInertList.stream().map(i -> new SyncRecordItemReq(i.getId(), i.getPlatformOrderNo(), storeDo.getId(), storeDo.getCompanyId())).collect(Collectors.toList());
        rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformOrder_SyncRecord_Update, JSON.toJSONString(new PlatformOrderSyncRecordReq(req.getSyncId(), 2, new Date(), null, null, platInertList.size(), items)));
        return "";
    }

    private Map<String, String> httpGet(String url, PlatformStoreDo shopDo, Date startDate, Date endDate) {
        Map<String, String> map = new HashMap<>();
        if (!url.contains("page_info")) {
            String parseStartDate = "";
            String parseEndDate = "";
            //传格林威治时区时间
            if (startDate != null) {
                parseStartDate = TimeUtils.formatDate(startDate, "yyyy-MM-dd'T'HH:mm:ss", "GMT");
                url = url + "&updated_at_min=" + parseStartDate;
            }
            if (endDate != null) {
                parseEndDate = TimeUtils.formatDate(endDate, "yyyy-MM-dd'T'HH:mm:ss", "GMT");
                url = url + "&updated_at_max=" + parseEndDate;
            }
            url = url + "&limit=" + 200;
        }

        OkHttpClient.Builder client = this.getHttpClient();
        Request request = new Request.Builder().addHeader("Content-Type", "application/json;charset=utf-8")
                .addHeader("X-Shopify-Access-Token", shopDo.getAppSecret())
                .url(url)
                .get()
                .build();
        Response response = null;
        String body = "";
        try {
            response = client.build().newCall(request).execute();
            body = response.body().string();
            map.put("body", body);
            map.put("page", getNextpage(response.header("Link")));
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public OkHttpClient.Builder getHttpClient() {
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1081);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder client = OkHttpUtils.getUnsafeOkHttpClient().newBuilder();
        client.connectTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).retryOnConnectionFailure(true);
//        client.proxy(proxy);
        return client;
    }



    private String httpPost(String url, PlatformStoreDo storeDo, String requestBody) {
        OkHttpClient.Builder client = this.getHttpClient();
        Request request = new Request.Builder().addHeader("Content-Type", "application/json;charset=utf-8")
                .addHeader("X-Shopify-Access-Token", storeDo.getAppSecret())
                .url(url).post(RequestBody.create(MediaType.get("application/json"), requestBody)).build();
        Response response = null;
        String body = "";
        try {
            response = client.build().newCall(request).execute();
            body = response.body().string();
            return body;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    private String getNextpage(String link) {
        if (StringUtils.isBlank(link)) return link;
        String[] strings = link.replaceAll("<", "").replaceAll(">", "").split(",");
        for (String string : strings) {
            String[] split = string.split(";");
            String url = split[0];
            String type = split[1];
            if (type.contains("next")) {
                return url;
            }
        }
        return null;
    }


    @Override
    public void consumerUpdate(RakutenOrderUpdateConReq req) {
        for (PlatformOrderDo et : req.getEts()) {
            platformOrderDao.updateById(et);
        }
        List<Long> orderIds = req.getProducts().stream().map(PlatformOrderProductDo::getOrderId).distinct().collect(Collectors.toList());
        if (orderIds.isEmpty()) {
            return;
        }
//        platformOrderService.matchSystemSku(req.getProducts(), req.getStoreId(), req.getCompanyId(), req.getTenantId());
//        platformOrderProductDao.delete(new LambdaQueryWrapper<PlatformOrderProductDo>()
//                .in(PlatformOrderProductDo::getOrderId, orderIds));
//        platformOrderProductDao.insertPlatformOrderItems(req.getProducts());
    }


    @Override
    public void getFulfillmentOrders(Long storeId, String orderId) {
        PlatformStoreDo storeDo = platformStoreDao.selectById(storeId);
        this.getFulfillmentOrders(storeDo, orderId);
    }


    private List<OrderFulfillmentOrderEntity> getFulfillmentOrders(PlatformStoreDo storeDo, String orderId) {
        String url = "https://" + storeDo.getAppKey() + ".myshopify.com/admin/api/2025-01/orders/" + orderId + "/fulfillment_orders.json";
        OkHttpClient.Builder client = this.getHttpClient();
        Request request = new Request.Builder().addHeader("Content-Type", "application/json;charset=utf-8")
                .addHeader("X-Shopify-Access-Token", storeDo.getAppSecret())
                .url(url)
                .get()
                .build();
        String body = "";
        try {
            Response response = client.build().newCall(request).execute();
            body = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(body)) {
            return null;
        }
        //{"fulfillment_orders":[]}
        //{"errors":"Not Found"}
        JSONObject jsonObject = JSON.parseObject(body);
        System.out.println(jsonObject);
//        if (jsonObject == null) return new ArrayList<>();
//        JSONArray fulfillment_orders = jsonObject.getJSONArray("fulfillment_orders");
        List<OrderFulfillmentOrderEntity> data = JSON.parseArray(jsonObject.getString("fulfillment_orders"), OrderFulfillmentOrderEntity.class);
        return data;
//        return data;
    }

    private  String getDeliveryCompany(PlatformOrderDo orderDo) {
        String deliveryCompany = "";
        if ("Yamato".equalsIgnoreCase(orderDo.getLogisticsCarrier())) {
            deliveryCompany = "Yamato (JA)";
        }
        else if ("Sagawa".equalsIgnoreCase(orderDo.getLogisticsCarrier())) {
            deliveryCompany = "Sagawa (JA)";
        }
        else if ("Japan Post".equalsIgnoreCase(orderDo.getLogisticsCarrier())) {
            deliveryCompany = "Japan Post (JA)";
        }
        else if ("Seino".equalsIgnoreCase(orderDo.getLogisticsCarrier())) {
            deliveryCompany = "";
        }
        else if ("DHL".equalsIgnoreCase(orderDo.getLogisticsCarrier())) {
            deliveryCompany = "DHL Express";
        }
        else if ("FedEx".equalsIgnoreCase(orderDo.getLogisticsCarrier())) {
            deliveryCompany = "FedEx";
        }
        else if ("UPS".equalsIgnoreCase(orderDo.getLogisticsCarrier())) {
            deliveryCompany = "UPS";
        }
        else if ("USPS".equalsIgnoreCase(orderDo.getLogisticsCarrier())) {
            deliveryCompany = "USPS";
        }
        return deliveryCompany;
    }


    @Override
    public void markShip(Long id) {
        PlatformOrderDo orderDo = platformOrderDao.selectById(id);
        if (orderDo == null) {
            return;
        }
        PlatformStoreDo storeDo = platformStoreDao.selectById(orderDo.getStoreId());
        String deliveryCompany = this.getDeliveryCompany(orderDo);
        List<PlatformOrderTrackDo> trackDos = platformOrderTrackDao.selectList(new LambdaQueryWrapper<PlatformOrderTrackDo>()
                .in(PlatformOrderTrackDo::getOrderId, id));

        List<String> collect = trackDos.stream().map(PlatformOrderTrackDo::getTrackNumber).collect(Collectors.toList());
        String fulfillment = this.createFulfillment(storeDo, orderDo.getBasketId(), deliveryCompany, collect);
        List<OperateRecordDo> operateRecordDos = new ArrayList<>();
        if (StringUtils.isNotBlank(fulfillment)) {
            //説明失敗了
            platformOrderService.updateMarkStatus(Collections.singletonList(orderDo.getId()), 2, fulfillment);
            OperateRecordDo operateRecordDo = new OperateRecordDo(id, OperateTypeEnum.PlatformOrder.getValue(), SysConstant.platformOrder_MarkShip_Fail, null, new Date(), fulfillment);
            operateRecordDos.add(operateRecordDo);
        }
        else {
            platformOrderService.updateMarkStatus(Collections.singletonList(orderDo.getId()), 3, null);
            OperateRecordDo operateRecordDo = new OperateRecordDo(id, OperateTypeEnum.PlatformOrder.getValue(), SysConstant.platformOrder_MarkShip, null, new Date(), StringUtils.join(collect, ","));
            operateRecordDos.add(operateRecordDo);
        }
        List<List<OperateRecordDo>> partition = ListUtil.partition(operateRecordDos, 3000);
        for (List<OperateRecordDo> partList : partition) {
            rabbitTemplate.convertAndSend(RabbitQueueConstant.CrossMall_CMOrder_OperateList, JSON.toJSONString(partList));
        }
    }


    public String createFulfillment(PlatformStoreDo storeDo, String orderId, String company, List<String> trackNo) {
        if (StringUtils.isBlank(company)) {
            return "未匹配快递公司Code";
        }
        if (trackNo == null || trackNo.isEmpty()) {
            return "快递单号为空";
        }
        List<OrderFulfillmentOrderEntity> fulfillmentOrders = this.getFulfillmentOrders(storeDo, orderId);
        if (fulfillmentOrders == null) {
            return "获取发运信息异常";
        }
        if (fulfillmentOrders.isEmpty()) {
            return "无发运信息";
        }
        List<OrderFulfillmentOrderEntity> unClosedFulfillment = fulfillmentOrders.stream().filter(orderFulfillmentOrderEntity -> !orderFulfillmentOrderEntity.getStatus().equals("closed")).collect(Collectors.toList());
        if (unClosedFulfillment.isEmpty()) {
            return null;
        }
        String addUrl = "https://" + storeDo.getAppKey() + ".myshopify.com/admin/api/2025-01/fulfillments.json";
        Map<String, Object> paraMap = new HashMap<>();
        List<FulfillmentOrderLineItems> itemList = new ArrayList<>();
        for (OrderFulfillmentOrderEntity.LineItemsDTO item : unClosedFulfillment.get(0).getLineItems()) {
            FulfillmentOrderLineItems itemsDTO = new FulfillmentOrderLineItems(item.getId(), item.getFulfillableQuantity());
            itemList.add(itemsDTO);
        }
        LineItemsByFulfillmentOrder lineItem = new LineItemsByFulfillmentOrder();
        lineItem.setFulfillmentOrderId(unClosedFulfillment.get(0).getId());
        lineItem.setFulfillmentOrderLineItems(itemList);
        List<LineItemsByFulfillmentOrder> lineItemsByFulfillmentOrder = new ArrayList<>();
        lineItemsByFulfillmentOrder.add(lineItem);

        ShopifyAddFulfillment fulfillment = new ShopifyAddFulfillment();
        fulfillment.setLineItemsByFulfillmentOrder(lineItemsByFulfillmentOrder);
        fulfillment.setNotifyCustomer(false);
        TrackingInfo trackingInfo = new TrackingInfo(trackNo.get(0).replaceAll("-", "").trim(), "", company);
        fulfillment.setTrackingInfo(trackingInfo);
        paraMap.put("fulfillment", fulfillment);

        log.error("shopify标发开始，参数：" + JSON.toJSONString(paraMap));
        String body = this.httpPost(addUrl, storeDo, JSON.toJSONString(paraMap));
        log.error("shopify标发結束，返回：" + body);

        if (StringUtils.isBlank(body)) {
            //连接异常
            return "标发 shopify服务器连接异常";
        }
        JSONObject jsonObject = JSON.parseObject(body);
        if (jsonObject.getJSONObject("fulfillment") != null) {
            //标发成功
            return null;
        }
        else {
            //标发失败
            String errors = jsonObject.getString("errors");
//            JSONArray base = errors.getJSONArray("base");
//            String string = base.getString(0);
//            if (string != null && string.contains("already fulfilled")) {
//                //                    doUpdateTrackNumber(shopifyShipDoList, shopDo, shopifyDo, shopifyRequestReq);
//            }
            return errors;
        }



    }

}
